<template>
  <div class="app-container">
    <div v-show="!purchAppDetailinfo.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query"
          :query-more-json="false"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="filterInfo.clearType"
        >
          <template v-slot:filter-coreFiscalPeriodId>
            <el-input
              v-model="filterInfo.query.fiscalPeriodName"
              class="not-mongolia"
              type="input"
              :required="true"
              :disabled="true"
              :placeholder="'请选择会计区间'"
            >
            <template #append>
              <el-icon @click="checkFinance"><MoreFilled /></el-icon>
            </template>
            </el-input>
          </template>
          <template v-slot:filter-startDate>
            <el-date-picker
              v-model="time"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              align="right"
              :picker-options="$fn.pickerOptionsFn()"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[
                  new Date(2000, 1, 1, 0, 0, 0),
                  new Date(2000, 1, 1, 23, 59, 59),
                ]"
              @change="timeChange"
            ></el-date-picker>
          </template>
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList"></NewPageFilter>
      </div>
      <!-- 表格 -->
      <TableContainer
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :tab-index="true"
        :check-box="false"
        :summary="true"
        :summary-field-list="tableInfo.summaryFieldList"
        :all-summary="true"
        :all-summary-data="allSummaryData"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :api="tableInfo.api"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span
            v-if="$permission('purchApplicationPlanExecuteRate:detail')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.orderNo }}</span
          >
          <span v-else>{{ scope.row.orderNo }}</span>
        </template>
      </TableContainer>
    </div>
    <SelectFiscalPeriod
      v-if="selectFiscalInfo.visible"
      v-model:show-dialog="selectFiscalInfo.visible"
      :query="selectFiscalInfo.query"
      :save-empty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="callBackselectFinanceType"
    />
    <PageDialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </PageDialog>
    <PurchApplicationDetail
      v-if="purchAppDetailinfo.visible"
      v-model:visible="purchAppDetailinfo.visible"
      :table-row="purchAppDetailinfo.data"
      @returnBack="getList"
    />
  </div>
</template>

<script setup name="purchApplicationPlanExecuteRate">
import SelectFiscalPeriod from '@/components/SelectFiscalPeriod/index'
import PageDialog from '@/components/PageDialog'
import PurchApplicationDetail from '@/views/purch/application/detail'
import { fatchTemplateByCode } from '@/api/base'
import {
  getPurchApplicationPlanExecuteRate,
  exportPurchApplicationPlanExecuteRate,
  printPurchApplicationPlanExecuteRate,
  getPurchApplicationPlanExecuteRateAverageRate,
} from "@/api/dataQuery.js";
import { getDeptAll } from "@/api/core";
const { proxy } = getCurrentInstance();
const time = ref([]);
const filterInfo = ref({
  clearType: true,
  query: {
    sort: "planQty desc,stockQty desc,executeRate desc",
    isCoreFiscalPeriodQuery: false,
    startDate: "",
    endDate: "",
    deptId: "",
    coreFiscalPeriodId: "",
    statusMult: "4",
  },
  searchList: [
    {
      label: "会计区间",
      value: "coreFiscalPeriodId",
      slot: true,
      show: true,
    },
    {
      label: "创建时间",
      value: "startDate",
      event: search,
      slot: true,
      show: true,
    },
    {
      componentType: "slip-select",
      label: "部门",
      value: "deptIdMult",
      multiple: true,
      api: getDeptAll,
      query: { deptAuth: "id", status: "1", useTypeId: "1" },
      event: search,
    },
    {
      label: "状态",
      value: "statusMult",
      event: search,
      componentType: "select-model",
      code: "purch_application_status",
      multiple: true,
      show: true,
    },
  ],
  searchBtn: [{ type: "button", label: "搜索", event: search }],
  btnList: [
    {
      type: "button",
      label: "打印",
      event: print,
      show: proxy.$permission("purchApplicationPlanExecuteRate:print"),
    },
    {
      type: "button",
      label: "导出excel",
      event: exportExcel,
      show: proxy.$permission("purchApplicationPlanExecuteRate:excel"),
    },
  ],
});
const selectFiscalInfo = ref({
  visible: false,
  query: { fiscalType: 1 },
});
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: null,
  summaryFieldList: [
    { value: "planQty", formatter: proxy.$fn.TripartiteMethod },
    { value: "stockQty", formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [
    { label: "单号", value: "orderNo", type: "slot" },
    {
      label: "计划数量",
      value: "planQty",
      type: "column",
      sortable: true,
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: "入库数量",
      value: "stockQty",
      type: "column",
      sortable: true,
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: "执行率(%)",
      value: "executeRate",
      sortable: true,
      type: "column",
    },
  ],
});
const allSummaryData = ref({
  data: [],
  fieldList: [
    {
      label: "总计划数量",
      value: "planQty",
      type: "column",
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: "总入库数量",
      value: "stockQty",
      type: "column",
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: "总执行率",
      value: "executeRate",
      type: "column",
      formatter: proxy.$fn.qtyFormatter,
    },
  ],
});
const purchAppDetailinfo = ref({
  visible: false,
  title: "申购单明细",
  data: {},
});
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
});
const dialogInfo = ref({
  visible: false,
  title: "提示",
  btLoading: false,
  type: "",
  msg: "",
  width: "400px",
  flag: true,
  btList: [
    { label: "关闭", event: handleClose, show: true },
    {
      label: "打印",
      type: "primary",
      event: checkConfirm,
      show: true,
    },
  ],
});
watch(
  () => filterInfo.value.query.startDate,
  (val) => {
    if (!val) {
      time.value = null;
    }
  }
);

function checkFinance() {
  selectFiscalInfo.value.visible = true;
}
function callBackselectFinanceType(data) {
  if (data && data.id) {
    filterInfo.value.query['coreFiscalPeriodId'] = data.id
    filterInfo.value.query['fiscalPeriodName'] = data.name
    filterInfo.value.query.startDate = "";
    filterInfo.value.query.endDate = "";
    filterInfo.value.query.isCoreFiscalPeriodQuery = true;
  } else {
    filterInfo.value.query['coreFiscalPeriodId'] = ''
    filterInfo.value.query['fiscalPeriodName'] = ''
  }
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.startDate = val[0];
    filterInfo.value.query.endDate = val[1];
    filterInfo.value.query.coreFiscalPeriodId = "";
    filterInfo.value.query.isCoreFiscalPeriodQuery = false;
    filterInfo.value.query.fiscalPeriodName = ''
  } else {
    filterInfo.value.query.startDate = "";
    filterInfo.value.query.endDate = "";
  }
}
function getList() {
  if (
    !filterInfo.value.query.coreFiscalPeriodId &&
    !filterInfo.value.query.startDate
  ) {
    proxy.$message({
      message: "请选择会计区间或创建时间",
      type: "warning",
      duration: 3500,
      showClose: true,
    });
    return;
  } else if (
    filterInfo.value.query.coreFiscalPeriodId &&
    filterInfo.value.query.startDate
  ) {
    proxy.$message({
      message: "会计区间或创建时间只能同时选一个",
      type: "warning",
      duration: 3500,
      showClose: true,
    });
    return;
  }
  filterInfo.value.query.isCoreFiscalPeriodQuery = filterInfo.value.query
    .coreFiscalPeriodId
    ? true
    : false;
  tableInfo.value.api = getPurchApplicationPlanExecuteRate;
  tableInfo.value.refresh = Math.random();
  getSummary();
}
function search() {
  if (
    !filterInfo.value.query.coreFiscalPeriodId &&
    !filterInfo.value.query.startDate
  ) {
    proxy.$message({
      message: "请选择会计区间或时间区间",
      type: "warning",
      duration: 3500,
      showClose: true,
    });
    return;
  } else if (
    filterInfo.value.query.coreFiscalPeriodId &&
    filterInfo.value.query.startDate
  ) {
    proxy.$message({
      message: "会计区间或时间区间只能同时选一个",
      type: "warning",
      duration: 3500,
      showClose: true,
    });
    return;
  }
  filterInfo.value.query.isCoreFiscalPeriodQuery = filterInfo.value.query
    .coreFiscalPeriodId
    ? true
    : false;
  tableInfo.value.api = getPurchApplicationPlanExecuteRate;
  tableInfo.value.initCurpage = Math.random();
  tableInfo.value.refresh = Math.random();
  getSummary();
}
function pageInfo(obj) {
  page.value = obj;
}
// 关闭弹窗前的回调
function handleClose() {
  dialogInfo.value.visible = false;
}
function checkConfirm() {
  if (dialogInfo.value.type === "excel") {
    exportExcelList();
  } else if (dialogInfo.value.type === "print") {
    printList();
  }
  dialogInfo.value.visible = false;
  dialogInfo.value.msg = "";
}
function exportExcel() {
  if (
    !filterInfo.value.query.coreFiscalPeriodId &&
    !filterInfo.value.query.startDate
  ) {
    proxy.$message({
      message: "请选择会计区间或时间区间",
      type: "warning",
      duration: 3500,
      showClose: true,
    });
    return;
  } else if (
    filterInfo.value.query.coreFiscalPeriodId &&
    filterInfo.value.query.startDate
  ) {
    proxy.$message({
      message: "会计区间或时间区间只能同时选一个",
      type: "warning",
      duration: 3500,
      showClose: true,
    });
    return;
  }
  filterInfo.value.query.isCoreFiscalPeriodQuery = filterInfo.value.query
    .coreFiscalPeriodId
    ? true
    : false;
  dialogInfo.value.visible = true;
  dialogInfo.value.type = "excel";
  dialogInfo.value.msg = "请选择数据导出范围";
  dialogInfo.value.btList[1].label = "导出";
  dialogInfo.value.flag = true;
}
function exportExcelList() {
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogInfo.value.flag,
  };
  exportPurchApplicationPlanExecuteRate(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp);
    }
  });
}
function print() {
  if (
    !filterInfo.value.query.coreFiscalPeriodId &&
    !filterInfo.value.query.startDate
  ) {
    proxy.$message({
      message: "请选择会计区间或时间区间",
      type: "warning",
      duration: 3500,
      showClose: true,
    });
    return;
  } else if (
    filterInfo.value.query.coreFiscalPeriodId &&
    filterInfo.value.query.startDate
  ) {
    proxy.$message({
      message: "会计区间或时间区间只能同时选一个",
      type: "warning",
      duration: 3500,
      showClose: true,
    });
    return;
  }
  filterInfo.value.query.isCoreFiscalPeriodQuery = filterInfo.value.query
    .coreFiscalPeriodId
    ? true
    : false;
  dialogInfo.value.visible = true;
  dialogInfo.value.type = "print";
  dialogInfo.value.msg = "请选择当数据打印范围";
  dialogInfo.value.btList[1].label = "打印";
  dialogInfo.value.flag = true;
}
function printList() {
  fatchTemplateByCode({
    resourceCode: "purchApplicationPlanExecuteRate:print",
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0]);
      getPrintData(temp, dialogInfo.value.flag);
    }
  });
}
function getPrintData(temp, flag) {
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: flag,
  };
  printPurchApplicationPlanExecuteRate(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data);
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        };
      });
      proxy.$lodop.preview(temp, newData);
    }
  });
}
function showDetail(row) {
  purchAppDetailinfo.value.visible = true;
  purchAppDetailinfo.value.data = { id: row.orderId };
}
function getSummary() {
  getPurchApplicationPlanExecuteRateAverageRate(
    proxy.$fn.delEmptyAttribute(filterInfo.value.query)
  ).then((res) => {
    if (res && res.success) {
      let data = res.data;
      if (data) {
        allSummaryData.value.data = [
          {
            planQty: data.planQty,
            stockQty: data.stockQty,
            executeRate: data.executeRate,
          },
        ];
      } else {
        allSummaryData.value.data = [
          {
            planQty: 0,
            stockQty: 0,
            executeRate: 0,
          },
        ];
      }
    }
  });
}
</script>

<style scoped></style>
